package org.openstreetmap.gui.jmapviewer;

import edu.cicese.alz.GPSUtilities;

import javax.swing.ImageIcon;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;

/**
 * Created by: Eduardo Quintana Contreras
 * Date: 16/07/12
 * Time: 03:12 PM
 */
public class MapHome {

	private double lat, lon;
	private double lat1, lon1;
	private double lat2, lon2;

	private int homeRadius;

	private Color colorBackground, colorBorder;

	public MapHome(double lat, double lon, int homeRadius) {
		this(lat, lon, homeRadius, new Color(0, 0, 255, 50), new Color(0, 0, 255, 150));
	}

	public MapHome(double lat, double lon, int homeRadius, Color colorBackground, Color colorBorder) {
		this.lat = lat;
		this.lon = lon;
		this.homeRadius = homeRadius;
		this.colorBackground = colorBackground;
		this.colorBorder = colorBorder;

		double[] off1 = GPSUtilities.getLatLon(lat, lon, homeRadius * -1);
		lat1 = off1[0];
		lon1 = off1[1];

		double[] off2 = GPSUtilities.getLatLon(lat, lon, homeRadius);
		lat2 = off2[0];
		lon2 = off2[1];
	}

	public double getLat() {
		return lat;
	}

	public double getLon() {
		return lon;
	}

	public double getLat1() {
		return lat1;
	}

	public double getLon1() {
		return lon1;
	}

	public double getLat2() {
		return lat2;
	}

	public double getLon2() {
		return lon2;
	}

	private int getRadius(int x, int y, int minX, int minY, int maxX, int maxY) {
		int a = x - minX;
		int b = y - maxY;
		int hyp1 = (int) Math.sqrt(a * a + b * b);
		a = maxX - x;
		b = minY - y;
		int hyp2 = (int) Math.sqrt(a * a + b * b);

		if (hyp1 > hyp2) return hyp1;
		return hyp2;
	}

	public void paint(Graphics g, Point position, Point position1, Point position2, int zoom) {
		Graphics2D g2 = (Graphics2D) g;

		g2.setRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));

//		int radius = zoom > 15 ?
//				getRadius(position.x, position.y, position1.x, position2.y, position2.x, position1.y) : 20;
		int radius = getRadius(position.x, position.y, position1.x, position2.y, position2.x, position1.y);

		radius = radius >= 20 ? radius : 20;
		int diameter = radius * 2;

		Area area = new Area(new Ellipse2D.Double(position.x - radius, position.y - radius, diameter, diameter));
		g2.setColor(colorBackground);
		g2.setStroke(new BasicStroke());
		g2.fill(area);
		g2.setColor(colorBorder);
		g2.setStroke(new BasicStroke(2));
		g2.draw(area);

		g2.drawImage(new ImageIcon(getClass().getClassLoader().getResource("images/home.png")).getImage(),
				position.x - 11, position.y - 11, null);
	}
}
